package org.appmon.core.config;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

//import org.apache.catalina.loader.WebappClassLoader;
import org.appmon.core.agent.loader.LoadUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;




public class XmlReader {
	
	public static Map<String,Object> applist = new HashMap<String,Object>();
	
	public void getXmlConfig(String xmlConfigLocation) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchFieldException{
		
		 File appmonConfig = new File(xmlConfigLocation);
		 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		 Document doc = dBuilder.parse(appmonConfig);
		 doc.getDocumentElement().normalize();

		 NodeList nodes = doc.getElementsByTagName("class-package");
		 System.out.println("XML PATH : "+xmlConfigLocation);
		 String baseBuildPath = null , webBuildPath = null;
		 
		 Enumeration<URL> roots = XmlReader.class.getClassLoader().getResources("");
			while(roots.hasMoreElements()) {
				URL ul=roots.nextElement();
				System.out.println("URL : "+ul.getPath());	
				if(ul.getPath().contains(("/classes"))){
					baseBuildPath=ul.getPath();
				}else if(ul.getPath().contains(("/WEB-INF/lib"))){
					webBuildPath=ul.getPath();
				}else{
					System.out.println("Inadequate path");
				}									
			
			}
			TempTest tt=new TempTest();
			tt.Test();
/*			 Class clas = ClassLoader.getSystemClassLoader().loadClass("org.appmon.core.config.PackageBaseInfo");
			 Method main = clas.getMethod("getInstance", new Class[0]);
			 Object object=main.invoke(null, null);
			 System.out.println("Reflect obj : "+object.hashCode());
			 Field field = clas.getDeclaredField("classToInclude");
			 ArrayListMultimap map = (ArrayListMultimap)field.get(object);*/
		//	 field.setAccessible(true);
			 
		 for (int i = 0; i < nodes.getLength(); i++) {
			 Node node = nodes.item(i);

			 if (node.getNodeType() == Node.ELEMENT_NODE) { 
				 Element element = (Element) node;
				 String className=element.getAttribute("name");
				 if(className!=null || !className.isEmpty()){	
					 
					 String jarName=element.getAttribute("jar-name").trim();
					//* WebappClassLoader wb= (WebappClassLoader) XmlReader.class.getClassLoader();
					 
					//* synchronized(wb){					 
					//* wb.setDelegate(true);
					 
					
					 
					 
					 
					 BehaviourProperties behaviourProperties =new BehaviourProperties();
					// System.out.println("method hit :"+element.getAttribute("method-hit-count").equals("enable")+" : "+element.getAttribute("method-hit-count"));
					 if(jarName==null ||!jarName.isEmpty()){
						 behaviourProperties.setClasspath(webBuildPath+jarName+".jar");
					 }else{
						 behaviourProperties.setClasspath(baseBuildPath);
					 }
					 
					 behaviourProperties.setMethodCountable(element.getAttribute("method-hit-count").equals("enable"));
					 
					 PackageBaseInfo.getInstance().setClassToInclude(className, behaviourProperties);
					
				/*	 map.put(className, behaviourProperties);*/
					
					 
					//* wb.setDelegate(false);
					 applist.put(className,behaviourProperties);
					 
					//* }
				//	 File file  = new File(LoadUtils.extractJarUrlLocation());
				//	  URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/"); 
				//	  URL[]urarry= new URL[] {jarfile };
				//	  for(URL url : urarry){
				//		  System.out.println("URL : "+url.getFile());
				//	  }
				//	  URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
					  //Class loadedClass = cl.loadClass("com.mypackage.myclass");
					  
				//	 Class clas = cl.loadClass("org.appmon.core.config.PackageBaseInfo");
				//	 Class clas = ClassLoader.getSystemClassLoader().loadClass("org.appmon.core.config.PackageBaseInfo");
				//	 Method main = clas.getMethod("getInstance", new Class[0]);
					// singlePackage=main.invoke(null, null);
					// org.apache.catalina.loader.WebappClassLoader.
					 					// WebappClassLoader.
					
					// System.out.println("Reflect Loader :"+singleton..getClassLoader());
					
					 System.out.println("xml reader class :"+className);
				 }
				
				 System.out.println("xml 1 Hashcode : "+PackageBaseInfo.getInstance().hashCode());
				 //wb.setDelegate(false);
			 }
		 }
		 /*field.set(object, map);*/
		 System.out.println("xml view Hashcode : "+PackageBaseInfo.getInstance().hashCode());
		 
		 System.out.println("xml value : "+PackageBaseInfo.getInstance().getClassToInclude());
		 System.out.println("XML Classloader : "+PackageBaseInfo.class.getClassLoader());
		 System.out.println("XML MAIN Classloader : "+ClassLoader.getSystemClassLoader().getClass().getName());
	}
	
	

}
